package com.cooba.content_frament;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.cooba.R;
import com.cooba.activitys.integral.GoodsExchangeActivity;
import com.cooba.activitys.integral.IntegralDetailsActivity;
import com.cooba.activitys.login.LoginActivity;
import com.cooba.activitys.setting.SettingActivity;
import com.cooba.activitys.user.ChangNumberActivity;
import com.cooba.activitys.user.ShareActivity;
import com.cooba.activitys.user.UserInfoActivity;
import com.cooba.activitys.user.VideoHistoryActivity;
import com.cooba.application.MyApplication;
import com.cooba.bean.SignBean;
import com.cooba.bean.UserInfoBean;
import com.cooba.dialog.SignDialog;
import com.cooba.utils.CarURL;
import com.cooba.utils.Constants;
import com.cooba.utils.ServerURL;
import com.cooba.utils.SharedPreferencesUtil;
import com.cooba.utils.Utils;
import com.cooba.views.CircleImageView;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

/**
 * Created by Administrator on 2015/12/7.
 * me
 */
public class MeFrament extends Fragment implements View.OnClickListener {


    private MyReciver myReceiver;
    //头像
    private FrameLayout photo;
    private CircleImageView user_img;
    //设置
    private ImageView mIv_setting;
    //昵称
    private TextView tvname;
    //积分
    private TextView tv_integral;
    private LinearLayout me_integral_ll;
    private RelativeLayout me_goods_exchange_rl;
    private RelativeLayout me_share_rl;
    private RelativeLayout me_video_history_rl;
    private LinearLayout me_sign_ll;
    private TextView me_remain_flow;
    private String login_id;
    private String password;
    private UserInfoBean userinfobean;
    private BitmapUtils bitmapUtils;
    private String uuid;
    private String download_integral = "0";
    private HttpUtils httpUtils;
    private RequestParams params;
    private SignBean signbean;
    private SignDialog dialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constants.UPDATE_DATA);
        intentFilter.addAction(Constants.LOGOUT_ACTION);
        myReceiver = new MyReciver();
        getContext().registerReceiver(myReceiver, intentFilter);
    }

    @Nullable
    private View contentview;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (contentview == null) {
            contentview = initview(inflater);
        }
        return contentview;
    }


    //初始化控件
    private View initview(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.me_frament, null, false);
        bitmapUtils = new BitmapUtils(getContext());
        photo = (FrameLayout) view.findViewById(R.id.photo);
        user_img = (CircleImageView) view.findViewById(R.id.user_photo);
        tvname = (TextView) view.findViewById(R.id.id_name);
        tv_integral = (TextView) view.findViewById(R.id.integral_tv);
        mIv_setting = (ImageView) view.findViewById(R.id.iv_setting);
        me_remain_flow = (TextView) view.findViewById(R.id.remainflow_tv);
        me_integral_ll = (LinearLayout) view.findViewById(R.id.me_integral_ll);
        me_goods_exchange_rl = (RelativeLayout) view.findViewById(R.id.me_goods_exchange_rl);
        me_sign_ll = (LinearLayout) view.findViewById(R.id.me_sign_ll);
        me_video_history_rl = (RelativeLayout) view.findViewById(R.id.me_video_history_rl);
        me_share_rl = (RelativeLayout) view.findViewById(R.id.my_share);
        me_share_rl.setOnClickListener(this);
        me_integral_ll.setOnClickListener(this);
        me_video_history_rl.setOnClickListener(this);
        me_goods_exchange_rl.setOnClickListener(this);
        me_sign_ll.setOnClickListener(this);
        photo.setOnClickListener(this);
        mIv_setting.setOnClickListener(this);
        initData();//获取用户信息
        setFlow();
        return view;
    }


    private void initData() {
        login_id = SharedPreferencesUtil.getData(getContext(), "login_id", "");
        HttpUtils http = new HttpUtils();
        RequestParams params = new RequestParams();
        String url = ServerURL.httpUrl + ServerURL.GetUserInfo;
        if (!TextUtils.isEmpty(login_id)) {
            params.addQueryStringParameter("login_id", login_id);
            http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {
                @Override
                public void onSuccess(ResponseInfo<String> responseInfo) {
                    Log.e("wei", "链接服务器成功---" + responseInfo.result);
                    //JSON的解析过程
                    try {
                        userinfobean = new Gson().fromJson(responseInfo.result, UserInfoBean.class);
                        if (userinfobean.getStatus().equals("1")) {
                            SharedPreferencesUtil.saveData(getContext(),"login_state","1");
                            setUserInfo();
                        }else {
                            SharedPreferencesUtil.saveData(getContext(),"login_state","0");
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(HttpException error, String msg) {
                    Log.e("ss", "链接服务器失败");
                    SharedPreferencesUtil.saveData(getContext(), "login_state", "0");
                }
            });
        }
    }

    private void setUserInfo() {
        tvname.setText(TextUtils.isEmpty(userinfobean.getName())?"未设置":userinfobean.getName());
        tv_integral.setText(userinfobean.getAllTotalIntegral());
        if (userinfobean.getPhoto() != null) {
            bitmapUtils.display(user_img, userinfobean.getPhoto());
        }
    }

    private void setFlow() {
        MyApplication application = MyApplication.getMyApplication();
        if (application.getIsInCar()) {
            String remaminflow = SharedPreferencesUtil.getData(getContext(), "remainflow", "--");
            Log.d("wei", "流量:" + remaminflow);
            me_remain_flow.setText(remaminflow);
        }
    }

    private void setIntegral() {
        String allTotalIntegral = SharedPreferencesUtil.getData(getContext(), "allTotalIntegral", "");
        if (!TextUtils.isEmpty(allTotalIntegral)) {
            tv_integral.setText(allTotalIntegral);
        }
    }


    @Override
    public void onClick(View v) {
        Intent intent;
        String login_id = SharedPreferencesUtil.getData(getContext(), "login_id", "");
        String login_state=SharedPreferencesUtil.getData(getContext(),"login_state","0");
        switch (v.getId()) {
            case R.id.photo:
                if (tvname.getText().toString().trim().equals("游客登录")) {
                    intent = new Intent(getActivity(), LoginActivity.class);

                } else {
                    intent = new Intent(getActivity(), UserInfoActivity.class);

                }
                startActivity(intent);
                break;
            case R.id.iv_setting:
                intent = new Intent(getActivity(), SettingActivity.class);
                startActivity(intent);
                break;
            case R.id.me_integral_ll:
                if (TextUtils.isEmpty(login_id)&&login_state.equals("0")) {
                    Toast.makeText(getContext(), "未登录!", Toast.LENGTH_SHORT).show();
                    return;
                }
//                if (!Utils.isnumber(login_id)){
//                    showBindDialog();
//                    return;
//                }
                intent = new Intent(getActivity(), IntegralDetailsActivity.class);
                intent.putExtra("allTotalIntegral", tv_integral.getText().toString());
                startActivity(intent);
                break;
            case R.id.me_goods_exchange_rl:
//                if (TextUtils.isEmpty(login_id)) {
//                    Toast.makeText(getContext(), "未登录!", Toast.LENGTH_SHORT).show();
//                    return;
//                }
                intent = new Intent(getActivity(), GoodsExchangeActivity.class);
                startActivity(intent);
                break;
            case R.id.me_sign_ll:
                if (TextUtils.isEmpty(login_id)&&login_state.equals("0")) {
                    Toast.makeText(getContext(), "未登录!", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (dialog!=null&&dialog.isShowing()){

                }else {
                    checkSign();
                }
                break;
            case R.id.me_video_history_rl:
                intent = new Intent(getActivity(), VideoHistoryActivity.class);
                startActivity(intent);
                break;
            case R.id.my_share:
                intent = new Intent(getActivity(), ShareActivity.class);
                startActivity(intent);
                break;
        }
    }

    private void checkSign() {
        httpUtils = new HttpUtils();
        params = new RequestParams();
        String login_id = SharedPreferencesUtil.getData(getContext(), "login_id", "");
        params.addBodyParameter("login_id", login_id);
        String urlsigncheck = ServerURL.httpUrl + ServerURL.signCheck;
        httpUtils.send(HttpRequest.HttpMethod.POST, urlsigncheck, params, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
                Log.e("wei", "校验失败");
                Toast.makeText(getContext(), "无网络!", Toast.LENGTH_SHORT).show();
                //me_sign_ll.setClickable(true);
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.e("wei", "校验成功" + responseInfo.result);
                try {
                    signbean = new Gson().fromJson(responseInfo.result, SignBean.class);
                    if (signbean.getStatus().equals("1")) {
                        dialog = new SignDialog(getActivity(), R.style.custom_dialog, R.layout.sign_dialog, signbean, new SignDialog.DialogListener() {
                            @Override
                            public void sign() {
                                doSign();
                            }
                        });
                        dialog.setCanceledOnTouchOutside(true);
                        android.view.Window window = dialog.getWindow();
                        window.setGravity(Gravity.CENTER);
                        dialog.show();
                    }
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                    Toast.makeText(getContext(), "数据解析异常,请检查网络链接!", Toast.LENGTH_SHORT).show();
                }
                //me_sign_ll.setClickable(true);

            }
        });
    }

    private void doSign() {
        httpUtils = new HttpUtils();
        params = new RequestParams();
        String login_id = SharedPreferencesUtil.getData(getContext(), "login_id", "");
        params.addBodyParameter("login_id", login_id);
        String urlsign = ServerURL.httpUrl + ServerURL.userSign;
        httpUtils.send(HttpRequest.HttpMethod.POST, urlsign, params, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
                Log.e("wei", "签到失败");
                Toast.makeText(getContext(), "无网络!", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.e("wei", "签到成功" + responseInfo.result);
                String msg = JSON.parseObject(responseInfo.result).getString("msg");
                String status = JSON.parseObject(responseInfo.result).getString("status");
                if (status.equals("1")) {
                    String allTotalIntegral = JSON.parseObject(responseInfo.result).getString("allTotalIntegral");
                    if (msg.contains("交易成功")) {
//                          SharedPreferencesUtil.saveData(getContext(), "allTotalIntegral", allTotalIntegral);
//                        setIntegral();
                        Toast.makeText(getContext(), "签到成功!", Toast.LENGTH_SHORT).show();
                        initData();

                    } else {
                        Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }

    private class MyReciver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Constants.UPDATE_DATA)) {
                initData();
            }
            if (intent.getAction().equals(Constants.LOGOUT_ACTION)) {
                logout();
            }
        }
    }

    private void logout() {
        tvname.setText("游客登录");
        tv_integral.setText("- -");
        user_img.setImageResource(R.mipmap.photo_background2);
    }

    private void getMac() {
        final MyApplication application = MyApplication.getMyApplication();
        if (application.getIsInCar()) {
            HttpUtils httpUtils = new HttpUtils();
            RequestParams params = new RequestParams();
            httpUtils.send(HttpRequest.HttpMethod.POST, CarURL.wifiDog, params, new RequestCallBack<String>() {
                @Override
                public void onSuccess(ResponseInfo<String> responseInfo) {
                    Log.d("wei", "链接服务器成功数据是:" + responseInfo.result);
                    String mac = null;
                    String remainFlow = null;
                    try {
                        mac = JSON.parseObject(responseInfo.result).getString("mac");
                        remainFlow = JSON.parseObject(responseInfo.result).getString("remainFlow");
                        SharedPreferencesUtil.saveData(getContext(), "wifimac", mac);
                        SharedPreferencesUtil.saveData(getContext(), "remainflow", Utils.FormatSize(Double.valueOf(remainFlow)));
                        setFlow();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }

                @Override
                public void onFailure(HttpException error, String msg) {
                    Log.d("wei", "链接服务器失败:" + msg);
                }
            });
        }
    }

    //显示绑定对话框
    public void showBindDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle("尚未绑定手机号,是否绑定?");
        builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(getActivity(), ChangNumberActivity.class);
                startActivity(intent);
            }
        });
        AlertDialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (myReceiver != null) {
            getContext().unregisterReceiver(myReceiver);
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        Log.d("wei", "Me:" + isVisibleToUser);
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d("wei", "resume");
        getMac();
    }
}
